﻿create PROCEDURE Sync.SP_VacationYearDays_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @VacationYearDays_Temp TABLE 
		(
			VacationYearDayID UniqueIdentifier,
			[VacationYearID] uniqueidentifier,
				[Day] datetime,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @VacationYearDays_Temp 
	   SELECT	Tbl.Col.value('VacationYearDayID[1]','uniqueidentifier') VacationYearDayID,
                Tbl.Col.value('VacationYearID[1]', 'uniqueidentifier') [VacationYearID],
Tbl.Col.value('Day[1]', 'datetime') [Day],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/VacationYearDays') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[VacationYearDays] ([VacationYearDayID],[VacationYearID],[Day])
	SELECT t.[VacationYearDayID],t.[VacationYearID],t.[Day]
	FROM  @VacationYearDays_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.VacationYearDays_Tracking s
        WHERE t.VacationYearDayID = s.VacationYearDayID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[VacationYearDays]
	SET [VacationYearDays].[VacationYearID] = t.[VacationYearID],[VacationYearDays].[Day] = t.[Day] 
	FROM [dbo].[VacationYearDays] s JOIN @VacationYearDays_Temp t 
    ON t.VacationYearDayID = s.VacationYearDayID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.VacationYearDays_Tracking r
				  WHERE t.VacationYearDayID = r.VacationYearDayID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[VacationYearDays]
    FROM @VacationYearDays_Temp t JOIN [dbo].[VacationYearDays] s
    ON t.VacationYearDayID = s.VacationYearDayID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END











